package cn.tedu.net;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

/**
 * 最终版本
 */
public class ChatServer {

    private List<PrintWriter> allOuts = new ArrayList<>();

    public ChatServer() throws Exception{
        ServerSocket server = new ServerSocket(8080);
        System.out.println("服务启动成功，准备等待链接：");
        while(true){
            Socket socket = server.accept();
            System.out.println("链接成功");
            ClientHandler clientHandler = new ClientHandler(socket);
            clientHandler.start();
        }

    }


    class ClientHandler extends  Thread{
        private Socket socket ;
        public ClientHandler(Socket socket){
            this.socket = socket;
        }
        @Override
        public void run() {
            try {
                // 准备读入数据
                InputStream in = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(in);
                BufferedReader br = new BufferedReader(isr);

                // 准备写出数据的流存储到集合
                OutputStream os = socket.getOutputStream();
                OutputStreamWriter osw = new OutputStreamWriter(os);
                BufferedWriter bw = new BufferedWriter(osw);
                PrintWriter pw = new PrintWriter(bw,true);
                synchronized (allOuts){
                    allOuts.add(pw);
                }

                // 一直读
                String line = null;
                while((line = br.readLine())!=null){
                    System.out.println(line);
                    // 群发
                    for (PrintWriter allOut : allOuts) {
                        allOut.println(line);
                    }
                }

               pw.close();
               br.close();

            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static void main(String[] args) throws Exception{
        ChatServer chatServer =  new ChatServer();
    }

}
